﻿#include "ffwebsocketsignalclient.h"
using namespace FF_WEBRTC_SIGNAL;

FFWebSocketSignalClient::FFWebSocketSignalClient(FFWebSocketSignalObserver* callback_)
{
    callback = callback_;
}

FFWebSocketSignalClient::~FFWebSocketSignalClient()
{

}

//封装offer格式的JSON发送到对端
void FFWebSocketSignalClient::sendOffer(const std::string offer, std::string remoteUid_)
{
    remoteUid = remoteUid_;

    json JMsg;
    JMsg["cmd"] = SIGNAL_TYPE_OFFER;
    JMsg["msg"] = offer;
    JMsg["roomId"] = roomId;
    JMsg["uid"] = uid;
    JMsg["remoteUid"] = remoteUid;

    send(JMsg.dump());
}

//封装answer格式的JSON发送到对端
void FFWebSocketSignalClient::sendAnswer(const std::string answer, std::string remoteUid_)
{
    remoteUid = remoteUid_;

    json JMsg;
    JMsg["cmd"] = SIGNAL_TYPE_ANSWER;
    JMsg["msg"] = answer;
    JMsg["roomId"] = roomId;
    JMsg["uid"] = uid;
    JMsg["remoteUid"] = remoteUid;

    send(JMsg.dump());
}

//封装candidate格式的JSON发送到对端
void FFWebSocketSignalClient::sendCandidate(const std::string candidate, std::string remoteUid_)
{
    remoteUid = remoteUid_;

    json JMsg;
    JMsg["cmd"] = SIGNAL_TYPE_CANDIDATE;
    JMsg["msg"] = candidate;
    JMsg["roomId"] = roomId;
    JMsg["uid"] = uid;
    JMsg["remoteUid"] = remoteUid;

    send(JMsg.dump());
}

//建立连接
void FFWebSocketSignalClient::on_open(websocketpp::connection_hdl hdl)
{
    std::cout << "Websocket连接服务器成功!" << std::endl;
    connected_ = true;
}

//断开连接
void FFWebSocketSignalClient::on_close(websocketpp::connection_hdl hdl)
{
    std::cout << "Websocket断开服务器成功!" << std::endl;
    connected_ = false;
}

//收到消息
void FFWebSocketSignalClient::on_message(websocketpp::connection_hdl hdl, client::message_ptr msg)
{
    std::cout << "on_message:" << msg->get_payload() << std::endl;
    try {
        json JMsg = json::parse(msg->get_payload());
        std::string cmd = JMsg["cmd"];

        if (cmd == SIGNAL_TYPE_NEW_PEER) { //new peer
            callback->handleRemoteNewPeer(JMsg);
        }
        else if (cmd == SIGNAL_TYPE_RESP_JOIN) { //self join
            callback->handleResponseJoin(JMsg);
        }
        else if (cmd == SIGNAL_TYPE_PEER_LEAVE) { //peer leave
            callback->handleRemotePeerLeave(JMsg);
        }
        else if (cmd == SIGNAL_TYPE_OFFER) { //offer
            callback->handleRemoteOffer(JMsg);
        }
        else if (cmd == SIGNAL_TYPE_ANSWER) { //answer
            callback->handleRemoteAnswer(JMsg);
        }
        else if (cmd == SIGNAL_TYPE_CANDIDATE) { //candidate
            callback->handleRemoteCandidate(JMsg);
        }

    }
    catch (std::exception const e) {
        std::cout << "JSON 解析失败：" << e.what() << std::endl;
    }
}

//连接失败
void FFWebSocketSignalClient::on_fail(websocketpp::connection_hdl hdl)
{
    std::cout << "连接服务器失败！" << std::endl;
}




